import os
from datetime import datetime

from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse

from App import models
from App.models import Article, Login, Article_type

#删除文章
from ArticleManage import words, download_type, outData
from Try import settings


def delete_article(request,aid,cid=-1,page=1):
    """

    :param request:
    :param aid: 文章id
    :param cid: 类别id
    :param page: 当前页码
    :return:
    """
    arcticle = Article.objects.get(pk=aid)
    if arcticle:
        arcticle.delete()
    return redirect(reverse("App:main", kwargs={'cid':cid,'page':page}))


#发布文章
def publish_article(request,cid=-1):
    error=""
    count=Article.objects.count()
    if request.method == "POST":
        title=request.POST.get("title")
        resource=request.POST.get("resource")
        author=request.POST.get("anthor")
        contend=request.POST.get("contend")
        time=datetime.now()
        download=0
        fobj = request.FILES.get('photo')
        path = os.path.join(settings.STATICFILES_DIRS[0],'upload')
        path = os.path.join(path,title+fobj.name)
        if fobj:
            with open(path,'wb') as target:
                # 源文件是否大于2.5M
                if fobj.multiple_chunks():
                    for data in fobj.chunks():
                        target.write(data)
                else:
                    target.write(fobj.read())
        title_=models.Article.objects.filter(title=request.POST['title'])
        if title_:
            error="已存在,请重新输入"
            return render(request,'wenzhang_xinwen_fabu.html',locals())
        else:
            cid=Article_type.objects.filter(cid=cid).first()
            wenzhang=models.Article.objects.create(
                aid=count+1,title=title,author=author,resource=resource,contend=contend,time=time,download=download,cid=cid
            )
            wenzhang.save()
            return redirect(reverse("App:main"))
    else:
        cid = cid if cid > 0 else Article_type.first_category().cid

        return render(request,'wenzhang_xinwen_fabu.html',locals())
#
#修改文章
def update_article(request,aid,cid):
    information=""
    if request.method=="POST":
        title = request.POST.get("title")
        resource = request.POST.get("resource")
        author = request.POST.get("author")
        contend = request.POST.get("contend")
        inuser = Article.objects.filter(title=request.POST['title'],resource=request.POST['resource'],author=request.POST['author'],contend=request.POST['contend'])
        if inuser:
            information='文章名已存在或者您没有修改'
            return render(request,'wenzhang_xinwen_info.html',locals())
        else:
            Article.objects.select_for_update().filter(aid=aid).update(title=title,author=author,resource=resource,contend=contend)
            return redirect(reverse('App:main'))
    return render(request,'wenzhang_xinwen_info.html',locals())

#显示文章的内容
def display(request,aid):
    contends=models.Article.objects.values("contend").filter(aid=aid)[0]
    info=models.Article.objects.get(aid=aid)
    contend=contends.get("contend")
    return render(request,'display.html',locals())

#用于对修改文章的跳转
def change_updata(request,aid,cid):
    article = Article.objects.get(aid=aid)
    return render(request,'wenzhang_xinwen_info.html',locals())

#文章内容翻译
def translate(request):
    import urllib.request
    import urllib.parse
    import json
    if request.method=="POST":

        trans_in = request.POST.get("translation")
        if trans_in[0:1].isalpha():
            trans_in=trans_in.replace("."," 。");
        else:
            trans_in=trans_in.replace("。",".")
            trans_in=trans_in.replace(";",".")
        # 删除url中的"_o"（translate_o），目的大概就是绕过有道翻译的反爬虫机制
        url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
        # 定义一个字典类型
        data = {}
        # 下面是有道官网中翻译的格式，用字典类型
        data['i'] = trans_in
        data['from'] = 'AUTO'
        data['to'] = 'AUTO'
        data['smartresult'] = 'dict'
        data['client'] = 'fanyideskweb'
        data['salt'] = '15736483975030'
        data['sign'] = 'c5ee4fdf9b43bd475606f9b2388a2cc3'
        data['ts'] = '1573648397503'
        data['bv'] = 'fa9b8d1fb8dd953b053f55751f710e64'
        data['doctype'] = 'json'
        data['version'] = '2.1'
        data['keyfrom'] = 'fanyi.web'
        data['action'] = 'FY_BY_REALTlME'

        # 把Unicode装换utf-8编码
        data = urllib.parse.urlencode(data).encode('utf-8')
        # 修改header，避免浏览器阻止访问
        req = urllib.request.Request(url, data)
        req.add_header('User-Agent',
                        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3732.400 QQBrowser/10.5.3819.400')
        response = urllib.request.urlopen(req)
        # utf-8装换成Unicode编码
        html = response.read().decode('utf-8')
        # 载入字符串html,得到一个字典类型
        target = json.loads(html)
        translate=target['translateResult'][0][0]['tgt']

        return render(request,'display.html',locals())

#用户删除
def user_delete(request,id):
    user = Login.objects.get(pk=id)
    if user:
        user.delete()
        users = Login.objects.all()
        return render(request,'userManager.html',locals())


def artiType_delete(request,cid):
    deleType=Article_type.objects.get(pk=cid)
    if deleType:
        deleType.delete()
        articleType = Article_type.objects.all()
        return render(request,'articleType.html',locals())

#修改文章类型
def artiType_modify(request,cid):
    article=Article_type.objects.get(cid=cid)
    if request.method=="POST":
        pname=request.POST.get("pname")
        Article_type.objects.select_for_update().filter(cid=cid).update(pname=pname)
        articleType = Article_type.objects.all()
        return render(request,'articleType.html',locals())
    return render(request,'articleType_modify.html',locals())

#添加文章类型
def artiType_addArticle(request):
    if request.method == "POST":
        pname = request.POST.get("pname")
        count = Article_type.objects.count()
        add = models.Article_type.objects.create(cid=count+1,pname=pname)
        add.save()
        articleType = Article_type.objects.all()
        return render(request, 'articleType.html', locals())
    return render(request, 'articleType_add.html', locals())

from aip import AipOcr
APP_ID = '23701409'
API_KEY = 'UCgaOAyzD5qUMFS3ffC0eVV9'
SECRET_KEY = 'sSsyHv8lVShc3bSVIXqYGQC46wHDsVFX'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()
def identify(request):
    if request.method=="POST":
        name=request.POST.get('identify')
        image = get_file_content('E:/djangoProject/Try/static/upload/' + name)
        data = client.basicAccurate(image)
        data = data.get('words_result')
        allStr = ""
        for word in data:
            allStr += word.get('words')
    return HttpResponse(allStr)

#文章爬取

def download(request):
    type_error=""
    if request.method=="POST":
        count=Article.objects.count()
        type=request.POST.get('download_type')
        start=request.POST.get('start_time')
        end=request.POST.get('end_time')
        p_exsist=models.Article_type.objects.filter(pname=type)
        if len(type)==0:
            type_error="类型不能为空,请重新输入！！！"
            return render(request,'addType.html',locals())
        if p_exsist:
            type_error="%s类型已存在,请重新输入！！！" % type
            return render(request,'addType.html',locals())
        elif type:
            download_type.main(type,start,end)
            count_type = Article_type.objects.count()
            outData.out(type, count,count_type+1)
            add = models.Article_type.objects.create(cid=count_type+1, pname=type)
            add.save()
        return redirect(reverse('App:main'))

